<template>
  <j-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <!-- 主表单区域 -->
      <a-form :form="form">
        <a-row>

          <a-col :xs="24" :sm="12">
            <a-form-item label="单号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['no', validatorRules.no]" placeholder="请输入单号"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="出库人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['outPersonName', validatorRules.outPersonName]" placeholder="请输入出库人"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="出人编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['outPersonCode', validatorRules.outPersonCode]" placeholder="请输入出人编码"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="出库时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择出库时间" v-decorator="['outTime', validatorRules.outTime]" :trigger-change="true" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="库房" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['storehouse', validatorRules.storehouse]" placeholder="请输入库房"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="状态 0正常1删除" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['state']" placeholder="请输入状态 0正常1删除" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="创建人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['createBy']" placeholder="请输入创建人"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="创建日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择创建日期" v-decorator="['createTime']" :trigger-change="true" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="更新人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['updateBy']" placeholder="请输入更新人"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="更新日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择更新日期" v-decorator="['updateTime']" :trigger-change="true" style="width: 100%"/>
            </a-form-item>
          </a-col>

        </a-row>
      </a-form>

      <!-- 子表单区域 -->
      <a-tabs v-model="activeKey" @change="handleChangeTabs">
        <a-tab-pane tab="采后物资出库子表" :key="refKeys[0]" :forceRender="true">
          <a-button   style='display: inline-block' type='primary' icon='plus' @click='bookinfoDialogModalShow'>新增22</a-button>
          <a-table
            :ref="refKeys[0]"
            :loading="flowerMaterialOutTable.loading"
            :columns="flowerMaterialOutTable.columns"
            :dataSource="flowerMaterialOutTable.dataSource"
            :maxHeight="300"
            :rowNumber="true"
             >

<!--            <template v-slot:numName='props'  >-->
<!--              <a-input @blur='numberChange(props)' >-->

<!--              </a-input>-->
<!--            </template>-->

            <template v-for="num in ['num']" :slot='num' slot-scope='text, record, index'
                      style='width: 100%;'>
              <div :key='num' style='float: left;margin-right: 0;width: 100%;'>
                <input v-model:value='record.num' style='width: 100%;' placeholder='请输入数量'
                       @change='numberChange(record)'  />
              </div>
            </template>
            <template slot='action' slot-scope='text, record'>
              <a-popconfirm v-if='varietyDataSource.length  && !disabled.isToMui ' title='确定删除?'
                            @confirm='() => outDelete(record)'>
                <a>删除</a>
              </a-popconfirm>
            </template>

<!--            <template v-slot:action="props">-->
<!--              <a @click="handleDelete(props)">删除</a>-->
<!--            </template>-->

          </a-table >
        </a-tab-pane>
      </a-tabs>

    </a-spin>






    <div>
      <!--  商品选择出库物品弹窗  -->
      <a-modal v-model:visible='this.bookinfoTable.visible' width='60%' title='商品选择' @ok='bookDialogOk'>
        <div style='margin-bottom: 10px'>
          <a-row style='margin-top: 10px'>
            <a-col :span='8'>
              <div style='display: inline-block;width: 45px;'>产品：</div>
              <div style='display: inline-block;width: 70%'>
                <a-input v-model='bookinfoTable.bookSerchParams.name' placeholder='请输入产品名称' allow-clear
                         @change='searchBookInfo' />
              </div>
            </a-col>
            <a-col :span='10'>
              <div style='display: inline-block;width: 80px;'>商品编码：</div>
              <div style='display: inline-block;width: 70%'>
                <a-input v-model='bookinfoTable.bookSerchParams.code' placeholder='请输入商品编码' allow-clear
                         @change='searchBookInfo' />
              </div>
            </a-col>
            <a-col :span='4'>
              <a-button type='primary' icon='search' @click='searchBookInfo'>
                查询
              </a-button>
            </a-col>
          </a-row>
        </div>
        <a-table :columns='bookinfoTable.columns'
                 :url='url.bookinfoList'
                 :data-source='bookinfoTable.dataSource'
                 :loading='bookinfoTable.loading'
                 :pagination="bookinfoTable.ipagination"
                 :row-selection="{selectedRowKeys: bookinfoTable.selectedRowKeys,type: 'radio',onChange:onSelectedChange}"
                 row-key='id'
                 ref="table"
                 size="middle"
                 @change="handleTableChange"
                 bordered
        ></a-table>
      </a-modal>
    </div>







  </j-modal>
</template>

<script>

  import pick from 'lodash.pick'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { FormTypes,getRefPromise } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import { validateDuplicateValue } from '@/utils/util'
  import JDate from '@/components/jeecg/JDate'
  import { getFlowerMaterialBook } from '@/api/api'
  import { getUuid } from '../../../utils/uuid'
  import { httpAction, getAction } from '@/api/manage'

  export default {
    name: 'FlowerMaterialOutMainModal',
    mixins: [JEditableTableMixin,JeecgListMixin],
    components: {
      JDate,
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
          no: {
            rules: [
              { required: true, message: '请输入单号!'},
            ]
          },
          outPersonName: {
            rules: [
              { required: true, message: '请输入出库人!'},
            ]
          },
          outPersonCode: {
            rules: [
              { required: true, message: '请输入出人编码!'},
            ]
          },
          outTime: {
            rules: [
              { required: true, message: '请输入出库时间!'},
            ]
          },
          storehouse: {
            rules: [
              { required: true, message: '请输入库房!'},
            ]
          },
        },
        refKeys: ['flowerMaterialOut', ],
        tableKeys:['flowerMaterialOut', ],
        activeKey: 'flowerMaterialOut',
        // 采后物资出库子表
        flowerMaterialOutTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '#',
              dataIndex: '',
              key:'rowIndex',
              width:40,
              align:"center",
              customRender:function (t,r,index) {
                return parseInt(index)+1;
              }
            },
            {
              title: '物资名称',
              key: 'name',
              dataIndex: 'name',
              type: FormTypes.input,
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled:true,
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '物资编码',
              key: 'code',
              dataIndex: 'code',
              type: FormTypes.input,
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled:true,
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '规格',
              key: 'specs',
              dataIndex: 'specs',
              type: FormTypes.input,
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled:true,
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '型号',
              key: 'modelname',
              dataIndex: 'modelname',
              type: FormTypes.input,
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled:true,
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '数量',
              key: 'num',
              dataIndex: 'num',
              type: FormTypes.slot,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue: '',
              slotName: "num",
              statistics: true,
              scopedSlots: { customRender: 'num' },
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },  {
              title: '单价',
              key: 'price',
              dataIndex: 'price',
              type: FormTypes.input,
              placeholder: '请输入${title}',
              disabled:true,
              defaultValue: '',
            },  {
              title: '总价',
              key: 'totalPrice',
              dataIndex: 'totalPrice',
              type: FormTypes.input,
              placeholder: '请输入${title}',
              disabled:true,
            }, {
              title: '操作',
              key: 'action',
              dataIndex: 'action',
              type: FormTypes.slot,
              slotName: "action"
            },

          ]
        },
        url: {
          add: "/flowermater/flowerMaterialOutMain/add",
          edit: "/flowermater/flowerMaterialOutMain/edit",
          flowerMaterialOut: {
            list: '/flowermater/flowerMaterialOutMain/queryFlowerMaterialOutByMainId'
          },
          list:"/flowermater/flowerMaterialBook/list",
          bookinfoList:"/flowermater/flowerMaterialBook/list",
        },


        bookinfoTable:{
          visible:false,//选择弹窗
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '#',
              dataIndex: '',
              key:'rowIndex',
              width:40,
              align:"center",
              customRender:function (t,r,index) {
                return parseInt(index)+1;
              }
            },
            {
              title:'库房',
              align:"center",
              dataIndex: 'storehouse_dictText'
            },{
              title:'成本中心',
              align:"center",
              dataIndex: 'cost_dictText'
            },{
              title:'物资名称',
              align:"center",
              dataIndex: 'name'
            },
            {
              title:'物资编码',
              align:"center",
              dataIndex: 'code'
            },
            {
              title:'规格',
              align:"center",
              dataIndex: 'specs'
            },
            {
              title:'型号',
              align:"center",
              dataIndex: 'modelname'
            },{
              title:'入库单位',
              align:"center",
              dataIndex: 'unit'
            }, {
              title:'计量单位',
              align:"center",
              dataIndex: 'unitMeasure'
            },
            {
              title:'总数量',
              align:"center",
              dataIndex: 'totalNum'
            },
            {
              title:'剩余数量',
              align:"center",
              dataIndex: 'num'
            },
            {
              title:'单价',
              align:"center",
              dataIndex: 'price'
            },{
              title:'总价',
              align:"center",
              dataIndex: 'totalPrice'
            },
            ],
          selectedRowKeys: [],
          bookSerchParams: {},
          selectedRow:[],
          ipagination:{
            current: 1,
            pageSize: 5,
            pageSizeOptions: ['10', '20', '30'],
            showTotal: (total, range) => {
              return range[0] + "-" + range[1] + " 共" + total + "条"
            },
            showQuickJumper: true,
            showSizeChanger: true,
            total: 0
          },

        },


      }
    },
    methods: {
      getAllTable() {

        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {

        let fieldval = pick(this.model,'no','outPersonName','outPersonCode','outTime','storehouse','state','createBy','createTime','updateBy','updateTime')
        this.$nextTick(() => {
          this.form.setFieldsValue(fieldval)
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.flowerMaterialOut.list, params, this.flowerMaterialOutTable)
        }
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          flowerMaterialOutList: allValues.tablesValue[0].values,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
     popupCallback(row){
       this.form.setFieldsValue(pick(row,'no','outPersonName','outPersonCode','outTime','storehouse','state','createBy','createTime','updateBy','updateTime'))
     },

      bookinfoDialogModalShow(){
        this.bookinfoTable.visible = !this.bookinfoTable.visible
        let params={}
        this.requestSubTableData(this.url.bookinfoList, params, this.bookinfoTable)
      },
      searchBookInfo(){
      //查找物品
        let params = {"name":this.bookinfoTable.bookSerchParams.name,"code":this.bookinfoTable.bookSerchParams.code}
       this.requestSubTableData(this.url.bookinfoList,params, this.bookinfoTable)
      },

      bookDialogOk(){
        if (JSON.stringify(this.bookinfoTable.selectedRow) !== '{}') {//判断this.selectVariety是否为空
          let varietyCodeFlag = false//第一个弹窗表格中的商品是否包含新添加的商品
          for (let item of this.flowerMaterialOutTable.dataSource) {
            if (item.code === this.bookinfoTable.selectedRow.code) {
              this.$message.error(`已添加过该商品( ${item.code} )`)
              varietyCodeFlag = true
              return
            }
          }
          if (!varietyCodeFlag) {
            this.bookinfoTable.selectedRow.maxNum=this.bookinfoTable.selectedRow.num
            this.bookinfoTable.selectedRow.num=null
            this.flowerMaterialOutTable.dataSource.push(this.bookinfoTable.selectedRow)
          }
        }
        this.bookinfoTable.visible = !this.bookinfoTable.visible
      },
      onSelectedChange(selectedRowKeys, selectionRows) {
        this.bookinfoTable.selectedRowKeys = selectedRowKeys// 如果不加这两行的话无法单选
        this.bookinfoTable.selectionRows = selectionRows
        this.bookinfoTable.selectedRow = selectionRows[0]
      },

      numberChange(record){
        if((record.num*10/10) > (record.maxNum *10/10 ) ){
          this.$message.error('填写数量不能超过库存数量' + record.maxNum)
          record.num = 0
          return
        }
        record.totalPrice=  (record.num*10/10)  * (record.price*10/10)
      },
      handleTableChange(pagination ) {
        //分页、排序、筛选变化时触发
        this.bookinfoTable.ipagination = pagination;
        let params = {"name":this.bookinfoTable.bookSerchParams.name,"code":this.bookinfoTable.bookSerchParams.code}
        this.requestSubTableData(this.url.bookinfoList, params, this.bookinfoTable)
      },
      /** 查询某个tab的数据 */
      requestSubTableData(url, params, tab, success) {
        let that = this
        params.pageNo=this.bookinfoTable.ipagination.current
        params.pageSize= this.bookinfoTable.ipagination.pageSize
        tab.loading = true
        getFlowerMaterialBook(params).then((res)=>{
          if (res.success) {
            tab.dataSource = res.result.records
            that.bookinfoTable.ipagination.total = res.result.total
          } else {
            that.$message.error(res.message)
          }
        }).finally(() => {
          tab.loading = false
        })
      },
      outDelete(record) {
        let { rowId, target } = props
        this.flowerMaterialOutTable.dataSource.splice(this.flowerMaterialOutTable.dataSource.indexOf(record), 1)
      },
      handleOk(){

        this.getAllTable().then(tables => {
          /** 一次性验证主表和所有的次表 */

          return validateFormAndTables(this.form, tables)
        }).then(allValues => {
          if (typeof this.classifyIntoFormData !== 'function') {
            throw this.throwNotFunction('classifyIntoFormData')
          }
          let formData = this.classifyIntoFormData(allValues)
          // 发起请求
          debugger
          return this.request(formData)
        }).catch(e => {
          if (e.error === VALIDATE_NO_PASSED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      },
      handleCancel(){
        this.visible = !this.visible
      }
    }
  }
</script>

<style scoped>
</style>